<template>
  <div class="app-container" id="app-container">
    <div class="bottom">
      <h1 class="title">智慧社区</h1>
      <div class="item oinput">
        <input class="select" type="text" v-model="telphone" placeholder="请输入手机号">
      </div>
      <div class="item login">
        <p @click="jump">授权登录</p>
      </div>
    </div>
  </div>
</template>
<script>
import router from '@/router'
import {
  getUserInfoByCode,
  getUserInfoById,
  saveOpenIdByUserTel,
  login
} from '@/api'
import {
  setToken,
  setDeviceId,
  setUserName,
  setUserId,
  setUserTel,
  setOpenId,
  getUnionId,
  getOpenId,
  setUnionId,
  setDeviceCode,
  setUserAddress,
  getToken,
  getUserId,
  setCanPay,
  setLastAmount
} from '@/utils/auth.js'
import { Toast } from 'vant'

export default {
  name: 'index',
  data () {
    return {
      commityname: '',
      telphone: '',
      deviceList: []
    }
  },
  created () {
    this.getCode()
  },
  methods: {
    // 截取URL获取code
    getUrlParam (name) {
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
      var r = window.location.search.substr(1).match(reg)
      console.log(r)
      if (r != null) { return unescape(r[2]) }
      return null
    },
    getCode () { // 非静默授权，第一次有弹框
      var local = window.location.href // 获取页面url
      this.code = this.getUrlParam('code') // 截取code
      console.log(this.code)
      this.getInfoByCode(this.code)
    },
    // 获取用户信息
    getInfoByCode (code) {
      console.log(code)
      getUserInfoByCode(code).then(res => {
        console.log(res)
        setUserName(res.data.userName)
        setUserId(res.data.userId)
        setUserTel(res.data.userTel)
        setOpenId(res.data.openId)
        setUnionId(res.data.unionId)
        setToken(res.data.token)
        this.$store.commit('isLogin', res.data.userId + '/' + res.data.userTel)
        // 判断是否注册
        this.deviceList = res.data.deviceList || []
        // 判断状态
        if (res.data.isRegistered) {
          router.push('/change')
        } else {
        }
      }).catch(err => {
        console.log(err)
      })
    },
    jump () {
      console.log('绑定手机号')
      const data = {
        openId: getOpenId(),
        unionId: getUnionId(),
        userTel: this.telphone
      }
      saveOpenIdByUserTel(data).then(res => {
        setUserName(res.data.userName)
        setUserId(res.data.userId)
        setUserTel(res.data.userTel)
        setOpenId(res.data.openId)
        setUnionId(res.data.unionId)
        setToken(res.data.token)
        this.deviceList = res.data.deviceList || []
        this.$store.commit('isLogin', res.data.userId + '/' + res.data.userTel)
        // 判断状态
        if (res.data.isRegistered) {
          router.push('/change')
        } else {
        }
      }).catch(err => {
        console.log(err.errorMsg)
      })
    }
  }
}
</script>
<style lang='scss' scoped>
@import "./index.scss";
</style>
